<?php


namespace App\Models\CacheModel;


use App\Models\Api\BaseCache;
use Exception;
use PDOStatement as PDOStatementAlias;
use think\Model;
use AstroTool\Cache\CacheManage;

/**
 * Vip&优惠券 常见问题 模型
 * Class ZlCommonProblems
 * @package App\Models\CacheModel
 */
class ZlCommonProblems extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zl_common_problems';
    protected $cacheModel = 'vip.common_problems';

    /**
     * 获取所有常见问题缓存
     * @return array|bool|mixed|PDOStatementAlias|string|Model
     * @throws Exception
     */
    public function getCommonProblemList()
    {
        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel)->getCache([], 'all');
        if (!$data)
        {
            $data = $this->getIdsFromDb(1);
            if (!$data) return [];
            CacheManage::getInstance()->setCacheConfig($this->cacheModel)->setCache($data, 'all', true);
        }

        $data = is_array($data) ? $data : json_decode($data, true);

        return $data;
    }


    /**
     * 获取所有常见问题缓存
     * @param string $id
     * @return array|bool|false|mixed|PDOStatementAlias|string|Model
     * @throws Exception
     */
    public function getCommonProblemDetail($id = '')
    {
        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $id)->getCache();
        if (!$data)
        {
            $data = $this->getDetailFromDb($id);
            if (!$data) return [];
            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $id)->setCache($data, 'details', true);
        }
        $data = is_array($data) ? $data : json_decode($data, true);

        return $data;
    }


    /**
     * 从数据库中获取所有问题的id
     * @param int $status
     * @return array|PDOStatementAlias|string|Model
     */
    protected function getIdsFromDb($status = 1)
    {
        $data = [];
        try
        {
            $data = $this->field('id,title')->where(['status' => $status])->order('sort DESC')->selectOrFail();
        }
        catch (Exception $e)
        {

        }

        return $data;
    }

    /**
     * 从数据库中获取 问题详情
     * @param $id
     * @return array|false|PDOStatementAlias|string|Model
     */
    private function getDetailFromDb($id = '')
    {
        $data = '';
        try
        {
            $data = $this->field('id,title,content')->where(['id' => $id])->findOrFail();
            $data = json_encode($data);
        }
        catch (Exception $e)
        {

        }

        return $data;
    }
}
